# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.


from ..glority_api.odoo_glority import OdooApi


import logging

_logger = logging.getLogger(__name__)


def api_get(fapiao_ocr):
    company = fapiao_ocr.company_id
    company_config = company.env['fp.company.glority'].search(
        [('company_id', '=', company.id)], limit=1)

    req_url = fapiao_ocr.ocr_provider_id.endpoint
    appkey = company_config.appkey
    app_secret = company_config.app_secret
    api = OdooApi(req_url, appkey, app_secret)
    return api


def ocr_fapiao(fapiao_check):
    # print('12345678890', 'ocr_fapiao', )

    result = []
    for one in fapiao_check:
        record = _api_ocr_fapiao(one)
        record2 = record.copy()
        record2['id'] = one.id
        result.append(record2)

    return result


def _api_ocr_fapiao(fapiao_ocr):
    fapiao = fapiao_ocr.fapiao_id
    attachment_id = fapiao.attachment_id

    # print('attachment_id', attachment_id)

    datas = attachment_id.datas

    b64str = datas.decode("utf-8")

    # print('attachment_id datas ', type(datas), datas)

    # print('attachment_id b64str ', type(b64str), b64str)

    values = {
        # 'image_url': 'http://47.97.127.82:80/dist/img/sample.jpg',
        # 'image_file': '',  # Binary
        'image_data': b64str,  # String Base64
    }

    api = api_get(fapiao_ocr)

    response = api.ocr_one(values)
    _logger.info('ocr fapiao...response:%s,', response)

    # return {}

    # error = response.get('error')
    # if error:
    #     # print('error', response)
    #     # return
    #     raise ValueError("check fapiao error for %s: %r" % (fapiao, response))

    result = response.get('result')
    if not result:
        # print('error', response)
        # return
        raise ValueError("check fapiao error for %s: %r" % (fapiao, response))

    # now = datetime.datetime.now()
    # api_check_date = now.strftime('%Y-%m-%d')
    # result['api_check_date'] = api_check_date

    return result
